// 全局变量
let currentUser = null;
let token = null;

// DOM元素
const loginPage = document.getElementById('login-page');
const registerPage = document.getElementById('register-page');
const passwordPage = document.getElementById('password-page');
const userPage = document.getElementById('user-page');
const messageAlert = document.getElementById('messageAlert');
const passwordLoginForm = document.getElementById('passwordLoginForm');
const smsLoginForm = document.getElementById('smsLoginForm');
const tabButtons = document.querySelectorAll('.tab-btn');

// 页面切换函数
function showPage(pageId) {
    document.querySelectorAll('.page').forEach(page => {
        page.classList.remove('active');
    });
    document.getElementById(pageId).classList.add('active');
}

// 显示消息提示
function showMessage(message, type = 'info') {
    messageAlert.textContent = message;
    messageAlert.className = `message-alert ${type}`;
    messageAlert.style.display = 'block';
    
    setTimeout(() => {
        messageAlert.style.display = 'none';
    }, 3000);
}

// 切换登录方式
function switchLoginForm(tab) {
    // 移除所有按钮的active类
    tabButtons.forEach(btn => btn.classList.remove('active'));
    // 移除所有表单的active类
    passwordLoginForm.classList.remove('active');
    smsLoginForm.classList.remove('active');
    
    // 添加当前按钮的active类
    const currentBtn = document.querySelector(`.tab-btn[data-tab="${tab}"]`);
    currentBtn.classList.add('active');
    
    // 显示对应的表单
    if (tab === 'password') {
        passwordLoginForm.classList.add('active');
    } else {
        smsLoginForm.classList.add('active');
    }
}

// 登录表单处理
passwordLoginForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    
    try {
        const response = await fetch('/api/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            token = data.token;
            currentUser = data.user;
            // 保存token到localStorage
            localStorage.setItem('token', token);
            window.location.href = 'user-info.html';
        } else {
            showMessage(data.message, 'error');
        }
    } catch (error) {
        showMessage('登录失败，请稍后重试', 'error');
    }
});

// 注册表单处理
document.getElementById('register-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const username = document.getElementById('register-username').value;
    const password = document.getElementById('register-password').value;
    const phone = document.getElementById('register-phone').value;
    const email = document.getElementById('register-email').value;
    
    try {
        const response = await fetch('/api/auth/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password, phone, email })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            showMessage('注册成功，请登录', 'success');
            showPage('login-page');
        } else {
            showMessage(data.message, 'error');
        }
    } catch (error) {
        showMessage('注册失败，请稍后重试', 'error');
    }
});

// 短信验证码发送
document.getElementById('sendSmsBtn').addEventListener('click', async () => {
    const phone = document.getElementById('phone').value;
    
    if (!phone) {
        showMessage('请输入手机号码', 'warning');
        return;
    }
    
    try {
        const response = await fetch('/api/auth/sms/send', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ phone })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            showMessage('验证码已发送', 'success');
            startCountdown();
        } else {
            showMessage(data.message, 'error');
        }
    } catch (error) {
        showMessage('发送失败，请稍后重试', 'error');
    }
});

// 倒计时功能
function startCountdown() {
    const button = document.getElementById('sendSmsBtn');
    let countdown = 60;
    button.disabled = true;
    
    const timer = setInterval(() => {
        countdown--;
        button.textContent = `${countdown}秒后重试`;
        
        if (countdown <= 0) {
            clearInterval(timer);
            button.disabled = false;
            button.textContent = '发送验证码';
        }
    }, 1000);
}

// 短信登录
document.getElementById('smsLoginForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const phone = document.getElementById('phone').value;
    const code = document.getElementById('smsCode').value;
    
    if (!phone || !code) {
        showMessage('请输入手机号和验证码', 'error');
        return;
    }
    
    fetch('/api/auth/login-by-code', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ phone, code })
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            if (data.data.needRegister) {
                // 需要注册，跳转到注册页面
                document.getElementById('register-phone').value = phone;
                showPage('register-page');
                showMessage('请设置用户名和密码完成注册', 'info');
            } else {
                // 已注册用户，直接登录
                localStorage.setItem('token', data.data.token);
                localStorage.setItem('user', JSON.stringify(data.data.user));
                showUserInfo(data.data.user);
                showPage('user-page');
                showMessage('登录成功', 'success');
            }
        } else {
            showMessage(data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showMessage('登录失败，请重试', 'error');
    });
});

// 显示用户信息
function showUserInfo(user) {
    if (!user) return;
    
    currentUser = user;
    document.getElementById('user-username').textContent = user.username || '';
    document.getElementById('user-phone').textContent = user.phone || '';
    document.getElementById('user-email').textContent = user.email || '';
}

// 更新用户信息显示
function updateUserInfo() {
    if (!currentUser) return;
    
    document.getElementById('user-username').textContent = currentUser.username;
    document.getElementById('user-phone').textContent = currentUser.phone;
    document.getElementById('user-email').textContent = currentUser.email;
    document.getElementById('user-token').textContent = token;
}

// 退出登录
document.getElementById('logout-btn').addEventListener('click', () => {
    token = null;
    currentUser = null;
    showPage('login-page');
    showMessage('已退出登录', 'info');
});

// 页面链接处理
document.querySelectorAll('a[data-page]').forEach(link => {
    link.addEventListener('click', (e) => {
        e.preventDefault();
        showPage(link.dataset.page);
    });
});

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    // 绑定切换事件
    tabButtons.forEach(btn => {
        btn.addEventListener('click', () => {
            const tab = btn.getAttribute('data-tab');
            switchLoginForm(tab);
        });
    });
    
    // 默认显示登录页面
    showPage('login-page');
    
    // 确保初始状态正确
    const activeTab = document.querySelector('.tab-btn.active');
    if (activeTab) {
        switchLoginForm(activeTab.getAttribute('data-tab'));
    }
}); 